﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CloudChartLib
{
    /// <summary>
    /// 离散扩展
    /// </summary>
    public class DiscreteExpand
    {
        private readonly int SourceNum;
        private readonly int TargetNum;

        private readonly double SegmentLen;

        /// <summary>
        /// 初始化离散扩展
        /// </summary>
        /// <param name="sourceNum">源序列数量</param>
        /// <param name="targetNum">目标序列数量</param>
        public DiscreteExpand(int sourceNum, int targetNum)
        {
            if (targetNum < sourceNum)
            {
                throw new Exception("目标数量需不小于源数量");
            }
            if (sourceNum < 2)
            {
                throw new Exception("源数量至少为2");
            }

            SourceNum = sourceNum;
            TargetNum = targetNum;

            SegmentLen = (TargetNum - 1.0) / (SourceNum - 1);
        }

        /// <summary>
        /// 获得目标点在源序列上的分段信息
        /// </summary>
        /// <param name="targetIndex">目标点索引</param>
        /// <param name="sourceStartIndex">源段起始索引</param>
        /// <param name="sourceStartDist">跟源段起始点的距离</param>
        public void GetSegmentInfo(int targetIndex, out int sourceStartIndex, out double sourceStartDist)
        {
            if (targetIndex == 0)
            {
                sourceStartIndex = 0;
                sourceStartDist = 0;
            }
            else if (targetIndex == TargetNum - 1)
            {
                sourceStartIndex = SourceNum - 2;
                sourceStartDist = 1;
            }
            else
            {
                sourceStartIndex = (int)(targetIndex / SegmentLen);
                sourceStartDist = targetIndex / SegmentLen - sourceStartIndex;
            }
        }
    }
}
